<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

<script>
    /** 
     * ============ 1.上级作用域 ============
    */
    console.log("============ 1.上级作用域 ============");
    var n = 10
    function fn() {
        var n = 20
        function f() {
            n++;
            console.log(n)
        }
        f()
        return f
    }


    var x = fn() // x就是函数名f
    x()
    x()
    console.log(n);

    /* 
        输出：
        21
        22
        23
        10
    */


    /** 
     * ============ 2.闭包 ============
    */
    console.log("============ 2.闭包 ============");
    var a = 0;
    function foo() {
        var b = 14;
        function fo() {
            console.log(a, b);
        }
        fo();
    }
    foo();

    /** 
     * ============ 3.经典面试题 ============
    */
    console.log("============ 3.1 for循环和闭包 ============");
    var data = [];
    for (var i = 0; i < 3; i++) {
        (function (j) {
            data[j] = function () {
                console.log(j);
            }
        })(i)
    }
    data[0]();
    data[1]();
    data[2]();


    console.log("============ 3.2 for循环和闭包 ============");
    var result = [];
    var a = 3;
    var total = 0;

    function func(a) {
        for (var k = 0; k < 3; k++) {
            result[k] = function () {
                total += k * a;
                console.log(total);
            }
        }
    }

    func(1);
    result[0]();  // 3
    result[1]();  // 6
    result[2]();  // 9

    console.log("============ 3.2 for循环和闭包 ============");
    // var result = [];
    // var a = 3;
    // var total = 0;

    // function func(a) {
    //     for (var k = 0; k < 3; k++) {
    //         (function (k) {
    //             result[k] = function () {
    //                 total += k * a;
    //                 console.log(total);
    //             };
    //         })(k);
    //     }
    // }

    // func(1);
    // result[0]();  // 0
    // result[1]();  // 1
    // result[2]();  // 3



</script>

</html>